import { getHost } from '@/utils/common/index'
import { checkStatus } from './helper/checkStatus'


export default function(reqData = {}) {

	if (reqData.loadingTip) {
		uni.showLoading({
			title: reqData.loadingTip,
			mask: true,
		});

		delete reqData.loadingTip;
	}

	return new Promise((resolve, reject) => {

		const token = uni.getStorageSync('token');
		if (token) {
			reqData.header ? reqData.header["Authorization"] = token : reqData.header = {
				Authorization: token,
			}
		}

		const { host } = getHost();
		reqData.url = host + reqData.url;

		reqData.success = function(res) {

			if (res.statusCode == 200) {

				if (res.header.Authorization) {
					uni.setStorageSync('token', res.header.Authorization);
				}
				let data = res.data;

				if (data && data.code !== 0 && reqData.errorAction !== false) {
					// * 有时候某个code不想显示默认tip
					const tipCodeExclude = reqData.tipCodeExclude;
					if (!tipCodeExclude || !tipCodeExclude.includes(data.code)) {
						uni.showToast({
							title: data.msg.toString() || '服务异常',
							icon: 'none',
						})
					}

					return reject(data);
				}

				return resolve(data.data);

			} else {
				if (reqData.errorAction !== false) {
					checkStatus(res);
				}
				return reject(res.data);
			}
		}

		reqData.fail = function() {
			reject();
			if (reqData.errorAction !== false) {
				uni.showToast({
					title: '服务异常',
					icon: 'none',
				});
			}
		}

		reqData.complete = function() {
			uni.hideLoading();
		}

		uni.request(reqData);
	})
}